import { Controller, Get, Post, Body } from '@nestjs/common';
import { ImageStore } from './image.entity';
import { QiniuService } from '../services/qiniu.service';
import { globalConfig } from '../config/globalConfig';

@Controller('/imagestore')
export class ImageStoreController {
    constructor(private qiniuService: QiniuService) {}

    @Post('/')
    async uploadImage(
        @Body()
        body: {
            // 图片地址
            src: string;
            /**
             * 是否允许超出配置的最大图片宽度
             * 有时候客户会上传特别大的图片 这时候为了节省流量 需要帮他切割
             * 见 globalConfig的maxImageStoreWidth
             */
            allowSizeOverflow: boolean;
        },
    ) {
        let item = new ImageStore(body);
        if (item.src.includes('?')) {
            item.src = await this.qiniuService.qiniuUploadHttpFile(item.src);
        }
        // 如果不是我的七牛资源需要重新上传
        if (!this.qiniuService.isImgSrcInQiniu(item.src)) {
            item.src = await this.qiniuService.qiniuUploadHttpFile(item.src);
        }
        // 如果大小超过了也需要重新上传
        let info = await this.qiniuService.qiniuImageInfo(item.src);
        if (
            !body.allowSizeOverflow &&
            (info.width > globalConfig.maxImageStoreWidth ||
                info.height > globalConfig.maxImageStoreWidth)
        ) {
            item.src = await this.qiniuService.qiniuUploadHttpFile(
                `${item.src}?imageView2/0/w/${globalConfig.maxImageStoreWidth}`,
            );
            info = await this.qiniuService.qiniuImageInfo(item.src);
        }
        item.size = info.size;
        item.width = info.width;
        item.height = info.height;
        await item.save();

        return item;
    }

    @Post('/changefolder')
    async changeFolder(@Body() opts: { images: string[]; folder: string }) {
        await ImageStore.updateMany(
            {
                _id: opts.images,
            },
            {
                folder: opts.folder,
            },
        );
    }
}
